package com.cwhuang.g7_tool_myhymns;

import java.util.ArrayList;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * @author G7
 *	DetailAddActivity負責
 *	1. 修改資料庫裡的詩歌
 *
 *
 *
 *
 */
public class DetailAddActivity extends Activity {
	AppHymns myHymns;
	public final static String COL_SERIAL = "col_serial";
	public final static String COL_INDEX = "col_index";
	public final static String COL_TITLE = "col_title";
	public final static String COL_RATING = "col_rating";
	public final static String COL_TIMES = "col_times";
	public final static String COL_FAMILIARITY = "col_familiarity";
	private Context context;
	private AutoCompleteTextView autoChooseHymn;
	private ArrayAdapter<String> autoChooseAdapter;
	private Spinner ratingSpinner;
	private String[] ratingItems;
	private ArrayAdapter<String> ratingAdapter;
	private Spinner familiaritySpinner;
	private String[] familiarityItems;
	private ArrayAdapter<String> familiarityAdapter;
	private Button btnSaveEdit;
	private Button btnEditAnother;
//	private HashMap<String, Object> nextHymn;				//這個活動要修改的詩歌
	private int nextSerial;
	private int nextIndex;
	private String nextTitle;
	private int nextRating;
	private int nextTimes;
	private String nextFamiliarity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_detail_add);
	    context = this;
	    myHymns = (AppHymns)getApplicationContext();
	    
	    getViews();
	    setClickListeners();

        //抓從statActivity.class或是最近新增那邊來的資料
        getFromIntent();
	}//END onCreate()
  
	private void setClickListeners() {
		//在autoChoose那選好後，馬上update舊有的星等&熟悉度資料到spinner那裏顯示
        autoChooseHymn.setOnItemClickListener(autoChooseHymnClickListener);
        //存入
        btnSaveEdit.setOnClickListener(saveEditListener);
        //再存一筆
        btnEditAnother.setOnClickListener(editAnotherListener);
	}	//END setClickListeners()

	private void getViews() {
		//自動完成：選擇要編輯的詩歌
	    //TODO 看能不能override他，把搜尋功能寫的可以不要只搜尋第一個字= =
	    autoChooseAdapter = new ArrayAdapter<String>(
	    		this,
                android.R.layout.simple_spinner_item, getHymnsArray()
                );
        autoChooseHymn = (AutoCompleteTextView)findViewById(R.id.auto_chooseHymn);
        autoChooseHymn.setAdapter(autoChooseAdapter);
        
        //spinner_rating:設星等
        ratingSpinner = (Spinner)findViewById(R.id.spinner_rating);
        ratingItems = getResources().getStringArray(R.array.ratings);
        ratingAdapter = new ArrayAdapter<String>(
        		this,
        		android.R.layout.test_list_item, 
        		ratingItems);
        	//setDropDownViewRecource可以避免setAdapter時，spinner變得又肥又醜
        ratingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ratingSpinner.setAdapter(ratingAdapter);
        ratingSpinner.setSelection(5);	//預設在0星等
        
        //spinner_familiarity:設熟悉度
        familiaritySpinner = (Spinner)findViewById(R.id.spinner_familiarity);
        familiarityItems = getResources().getStringArray(R.array.familiarity);
        familiarityAdapter = new ArrayAdapter<String>(
        		this, 
        		android.R.layout.test_list_item,
        		familiarityItems);
        familiarityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        familiaritySpinner.setAdapter(familiarityAdapter);
        familiaritySpinner.setSelection(4);		//預設在普通熟
        
        //存入的button
        btnSaveEdit = (Button)findViewById(R.id.btn_save);
        btnSaveEdit.setEnabled(false);

        //再存一筆的button
        btnEditAnother = (Button)findViewById(R.id.btn_edit_another);
        btnEditAnother.setEnabled(false);
	}	//END getViews()

	//處理從別的activity來的東西
	private void getFromIntent() {
		String index,
			   title;
		
		Bundle bundle = this.getIntent().getExtras();
		if(bundle!=null){
			//把鍵盤收起來
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
			
			index = bundle.getString(COL_INDEX);
			title = bundle.getString(COL_TITLE);
			String str = index + " " + title;
			autoChooseHymn.setText(str);
			getAndUpdate();
			//不要讓選單出現(終於成功了@@ shit 試了一個小時有吧
			autoChooseHymn.setHint(str);
			autoChooseHymn.setText("");
			
			//把再存一筆封閉
			btnEditAnother.setEnabled(false);
			
		}
	}	//END getFromIntent()
	
	//從autoText取得對應的資料，update 兩個spinner的資料
	public void getAndUpdate(){
		
		//TODO 把與IO外部檔案的程式，全部收到HymnsIO裡
		
		String text = autoChooseHymn.getText().toString();
		String[] result = text.split(" ");
		//result[0]是index，result[1]是title
		Log.d("results", "result1:"+result[0]+";result2:"+result[1]);
		
		//去對照找出符合我們所找的資料，並把資料取出來
//		for(Map<String, Object> hMap : myHymns.hymns){
		//加入後兩行改成取出hMap在hymns的位置，直接修改hymns也可，但用nextHymn較安全?
		//TODO 思考直接在int i=0時，把result[0]丟給0，可以省去很多搜尋的時間?
		for(int i=0;i<myHymns.hymns.size();i++){
			Log.d("i", "i是"+i);
			if (myHymns.hymns.get(i).get(COL_TITLE).toString().contains(result[1]) ) {
				nextSerial = Integer.parseInt(myHymns.hymns.get(i).get(COL_SERIAL).toString());
				nextTitle = myHymns.hymns.get(i).get(COL_TITLE).toString();
				nextIndex = Integer.parseInt(myHymns.hymns.get(i).get(COL_INDEX).toString());
				nextRating = Integer.parseInt(myHymns.hymns.get(i).get(COL_RATING).toString());
				nextTimes= Integer.parseInt(myHymns.hymns.get(i).get(COL_TIMES).toString());
				nextFamiliarity = myHymns.hymns.get(i).get(COL_FAMILIARITY).toString();
				
				//debug
				Log.d("i與serial","i:"+i+" ;serial:"+nextSerial+" ;title:"+nextTitle);
				
//				nextHymn.put(COL_SERIAL, hMap.get(COL_SERIAL));
//				nextHymn.put(COL_TITLE,hMap.get(COL_TITLE) );
//				nextHymn.put(COL_RATING,hMap.get(COL_RATING) );
//				nextHymn.put(COL_TIMES,hMap.get(COL_TIMES) );
//				nextHymn.put(COL_FAMILIARITY,hMap.get(COL_FAMILIARITY) );
				break;
			}
		}//END for
		
		//update在介面上看到的資料
//		String title=  nextHymn.get(COL_TITLE).toString();
//		int rating =  Integer.parseInt(nextHymn.get(COL_RATING).toString() );
//		int times =  Integer.parseInt(nextHymn.get(COL_TIMES).toString() );
//		String familiarity =  nextHymn.get(COL_FAMILIARITY).toString();
		ratingSpinner.setSelection(transformRating(nextRating) );
		Toast.makeText(context,nextTitle+"之前唱了"+nextTimes+"次",Toast.LENGTH_LONG).show();
		familiaritySpinner.setSelection(transformFamiliarity(nextFamiliarity) );
		
		//點完後，鍵盤可以自動收起來不要在那邊礙眼
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		
		//輸入完後，再點一下會把原本的字清空，不用再按刪除鍵
		autoChooseHymn.setHint(text);
		
		//只有在有輸入資料的時候，才能使用存入和再存一筆的button
		if(!text.equals(null)){
			btnSaveEdit.setEnabled(true);
			btnEditAnother.setEnabled(true);
		}
	}//END getAndUpdate()
	
	OnItemClickListener autoChooseHymnClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0,
				android.view.View arg1, int arg2, long arg3) 
		{
			getAndUpdate();
		}//onItemClick
	};//END autoChooseHymnClickListener
	
	//再存一筆：先存入，再呼叫新的DetailAddActivity.java
	View.OnClickListener editAnotherListener = new View.OnClickListener() {
		public void onClick(View v) {
			saveEdit();
			autoChooseHymn.setText("");
			autoChooseHymn.requestFocus();
		}
	};	//END editAnotherListener
	
	//存入：要把這些資料都輸進去myHymns.hymns，再於stop時寫入sd卡中，存完跳回前一頁
	View.OnClickListener saveEditListener = new View.OnClickListener() {
		public void onClick(View v) {
			saveEdit();
			
			//反正我只是要更新statActivity的資料
			Intent replyIntent = DetailAddActivity.this.getIntent();
			if(replyIntent!=null){
				setResult(RESULT_OK);
			}
			
	    	finish();		//再跳回前一頁
		}//END onClick
	};//END saveEditListener
	
	//fixed 重大bug: 存入的詩歌還是會有錯
	//存入的方法
	public void saveEdit(){
		//對照出nextHymn在hymns的位置，再把hymns替換掉：index = serial-1不行這樣~"~
		//int index = Integer.parseInt(nextHymn.get(COL_SERIAL).toString() )-1;
		nextRating = transformRating(ratingSpinner.getSelectedItemPosition() );
		nextFamiliarity = familiaritySpinner.getSelectedItem().toString();
		nextTimes += 1;
		
		//debug:因為存入後，如果有去看統計與排序，會讓serial和arraylist的index之間失去關聯
		//所以要馬是寫入前重新排序，要馬是寫入前重新搜尋= =
		//此時搜尋一定要用完全的字串相等才能存入，不能用contains?
		for(int i=0;i<myHymns.hymns.size();i++){
			Log.d("存入時的i", "i是"+i);
			if (myHymns.hymns.get(i).get(COL_TITLE).toString().equals(nextTitle) ) {
//				String titleNext=  nextHymn.get(COL_TITLE).toString();
				String titleHymn=  myHymns.hymns.get(i).get(COL_TITLE).toString();
				Log.d("nextHymn和hymns", "serial:"+nextSerial+"next:"+nextTitle+";hymn:"+titleHymn);
				//存入myHymns.hymns中
//				int times = Integer.parseInt(nextHymn.get(COL_TIMES).toString() );
//				myHymns.hymns.get(index).put(COL_RATING, nextHymn.get(COL_RATING));
//				myHymns.hymns.get(index).put(COL_FAMILIARITY, nextHymn.get(COL_FAMILIARITY));
//				myHymns.hymns.get(index).put(COL_TIMES, times+1);
				myHymns.hymns.get(i).put(COL_RATING, nextRating);
				myHymns.hymns.get(i).put(COL_TIMES, nextTimes);
				myHymns.hymns.get(i).put(COL_FAMILIARITY, nextFamiliarity);
				
				break;
			}
		}
		
		//替換完後，存入sd卡當中
    	HymnsIO hymnsIO = new HymnsIO();
    	hymnsIO.saveHymns(context);
		
    	Toast.makeText(context, nextIndex+" "+nextTitle+"已存入SD卡 :)~", Toast.LENGTH_SHORT).show();
    	//存完後強迫使用者一定要有新資料才能儲存
    	btnSaveEdit.setEnabled(false);
    	btnEditAnother.setEnabled(false);
	}//END saveEdit
	
	//從myHymns的hymns中取得index和title的資料，並合併為"1 頌讚獨一真神"形式
	public String[] getHymnsArray(){
		//回傳的array就是要包含所有這形式的歌曲
		//TODO 之後在statActivity那裡，要新增能搜尋所有欄位，並filter out有相同欄位的功能
		
		ArrayList<String> array = new ArrayList<String>();
		for(Map<String, Object> hMap : myHymns.hymns){
			String str = hMap.get(COL_INDEX).toString()+" "+hMap.get(COL_TITLE).toString();
			array.add(str);
		}
		//把arrayList轉為array的方法↓不然會出現錯誤
		return array.toArray(new String[array.size()]);
	}
	
	//轉換rating：要配合在ratings_arrays.xml的陣列順序
	public int transformRating(int rating) {
		int result;
		switch (rating) {
		case 5:
			result = 0;	//5星等
			break;
		case 4:
			result = 1;	//4星等
			break;
		case 3:
			result = 2;	//3星等
			break;
		case 2:
			result = 3;	//2星等
			break;
		case 1:
			result = 4;	//1星等
			break;
		case 0:
			result = 5;	//0星等
			break;
		default:
			result = 5; //0星等
			break;
		}
		
		return result;
	}//END transformRating
	
	//轉換familiarity：要配合在ratings_arrays.xml的陣列順序
	public int transformFamiliarity(String familiarity) {
		int value=4;
		if (familiarity.equals("極熟") ){value = 0;}
		else if (familiarity.equals("極不熟") ){value = 1;}
		else if (familiarity.equals("很熟") ){value = 2;}
		else if (familiarity.equals("不熟") ) {value = 3;}
		else if (familiarity.equals("普通熟") ) {value = 4;}
		else	value=4;
		
		return value;
	}//END transformFamiliarity
	
}//END DetailAddActivity.java